package com.zzyl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.RandomNicknameGeneratorUtil;
import com.zzyl.vo.LoginVo;
import lombok.Builder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;



@Service
@Builder
public class MemberServiceImpl implements MemberService {
    
    
    @Autowired
    private WechatService wechatService;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1、调用微信接口获取openid
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());
        // 2、根据openid查询会员表，判断当前微信用户是否存在
        Member member = memberMapper.selectByOpenId(openid);
        // 3、判断会员是否存在，如果不存在则自动注册
        if (member == null) {
            member = new Member();
            member.setOpenId(openid);
        }
        // 4、获取用户手机号

        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        //5、判断会员信息是否为空，新增或者更新用户信息
        saveOrUpdate(member, phone);

        // 6、生成登录成功的凭据 - JWT令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());
        String jwt = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(), jwtProperties.getTtl(), claims);
        return LoginVo.builder().token(jwt).nickName(member.getName()).build();
    }

    private void saveOrUpdate(Member member, String phone) {
        if (member.getId() == null) {
            member.setPhone(phone);
            member.setName(RandomNicknameGeneratorUtil.generateRandomNickname());
            memberMapper.insert(member);
        }else {
            if (!StrUtil.equals(member.getPhone(),phone)){
                member.setPhone(phone);
                memberMapper.updateSelective(member);
            }
        }
    }
}
